package com.eastseeway.radioproject.utils;

import android.util.Log;

import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.entities.BaseTCPBean;
import com.eastseeway.radioproject.entities.BeanOfSplitFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteOrder;

import struct.JavaStruct;
import struct.StructException;

public class FileSplitUtil {

    private static final int BUFFER_SIZE = 64;
    private static long totalSize = 0;
    private int i ;

    private static final byte PADDING_BYTE = 0x00;

    private FileInputStream mFileInputStream;
    private static String filePath = "";

    private FileSplitUtil() {
    }

    private static final class InstanceHolder {
        //    生成单例模式代码
        static final FileSplitUtil instance = new FileSplitUtil();
    }

    public static FileSplitUtil getInstance(String filePath1) {
        if (!filePath.equals(filePath1)) {
            totalSize = new File(filePath1).length()/64;
            Log.e("12121",filePath1+":总大小："+totalSize);
            filePath = filePath1;
        }
        return InstanceHolder.instance;
    }


    public BeanOfSplitFile getFileBytes(int address) {
        try {
            if (filePath.isEmpty()) return null;
            if (mFileInputStream == null) mFileInputStream = new FileInputStream(filePath);

            byte[] buffer = new byte[BUFFER_SIZE];// 定义缓冲区
            int len = mFileInputStream.read(buffer);// 存储读取的字节数
            int available = mFileInputStream.available();

            if (len == -1){
                mFileInputStream.close();
                mFileInputStream = null;
                filePath = "";
                totalSize = 0;
                i = 0;
                Log.e("12121", "文件读取完成！");
                return new BeanOfSplitFile("100%",null);
            }
            i++;
            BaseTCPBean baseTCPBean = new BaseTCPBean();
            baseTCPBean.setAddress(address);
            byte[] content;
            if (len == BUFFER_SIZE) {
                content = buffer;
            } else {
                // 如果最后一帧不足 BUFFER_SIZE，复制有效长度的字节
                content = new byte[len];
                System.arraycopy(buffer, 0, content, 0, len);
            }
            baseTCPBean.setContent(content);
//            Log.e("12121", "读取到的文件帧："+totalSize+" // "+i+" // " +len+" // "+ByteUtil.ByteArrToHex(buffer));
            float progress = i * 100f/totalSize;
            String progressStr = String.format("%.1f", progress) + "%";
            return new BeanOfSplitFile(progressStr,JavaStruct.pack(baseTCPBean, ByteOrder.LITTLE_ENDIAN));

        } catch (IOException | StructException e) {
            throw new RuntimeException(e);
        }
    }
}